package datastruct.queue;

/**
 * @author RunningShrimp
 * @date 2021/5/11  19:53
 * @see <a href=""></a>
 */
@SuppressWarnings("unchecked")
public class LoopQueue<E> implements Queue<E> {
    private E[] date;
    private int tail, front;
    private int size;

    public LoopQueue(int capacity) {
        this.date = (E[]) new Object[capacity + 1];
    }

    public LoopQueue() {
        this(10);
    }

    public int getCapacity() {
        return date.length - 1;
    }

    @Override
    public boolean isEmpty() {
        return tail == front;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalStateException("队列为空");
        }
        E e = date[front];
        date[front] = null;
        front = (front + 1) % date.length;
        size--;
        if (size == getCapacity() / 4 && getCapacity() / 2 == 0) {
            resize(getCapacity() / 2);
        }
        return e;
    }

    @Override
    public void enqueue(E e) {
        if ((tail + 1) % date.length == front) {
            resize(getCapacity() * 2);
        }
        date[tail] = e;
        tail = (tail + 1) % date.length;
        size++;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalStateException("队列为空");
        }
        return date[front];
    }

    @Override
    public int getSize() {
        return size;
    }

    /**
     * 将数组空间的容量变成newCapacity大小
     *
     * @param newCapacity 信容量大小
     */

    private void resize(int newCapacity) {

        E[] newData = (E[]) new Object[newCapacity + 1];
        for (int i = 0; i < size; i++) {
            newData[i] = date[(i + front) % date.length];
        }
        date = newData;
        front = 0;
        tail = size;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder(String.format("LoopQueue: size = %d,capacity = %d\n", size, getCapacity())).append("front [");
        for (int i = front; i != tail; i = (i + 1) % date.length) {
            sb.append(date[i]);
            if ((i + 1) % date.length != tail) {
                sb.append(", ");
            }
        }
        sb.append("] tail");
        return sb.toString();
    }
}
